package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.mapper.OverTimeMapper;
import com.ruan.pojo.*;
import com.ruan.pojoExt.BusinessTripExt;
import com.ruan.pojoExt.OverTimeExt;
import com.ruan.service.*;

import com.ruan.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/overTime")

public class OverTimeController {

    @Autowired
    private OverTimeMapper overTimeMapper;

    @Autowired
    private OverTimeService overTimeService;

    @Resource
    private OverTimeSetService overTimeSetService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    PositionService positionService;

    /**
     * 分页条件 查询员工加班列表
     * @param currentPage 当前页
     * @param pageSize 每页最大数
     * @param ltoQueryCondition 查询条件
     * @return
     */
    @PostMapping("/selectByPageAndCondition/{currentPage}/{pageSize}")
    public Result selectByPageAndCondition(@PathVariable int currentPage,
                                           @PathVariable int pageSize,
                                           @RequestBody LTOQueryCondition ltoQueryCondition) {

//        System.out.println("selectByPageAndCondition的参数是:"+ltoQueryCondition);
        Date month = ltoQueryCondition.getMonth();//2024-2-1
        IPage<OverTime> iPage=new Page<>(currentPage,pageSize);
        QueryWrapper<OverTime> queryWrapper = new QueryWrapper<>();

        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.like(ltoQueryCondition.getName()!=null,
                Employee::getName,ltoQueryCondition.getName());
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper1);

        List<Long> employeeIds = employeeList.stream().map(Employee::getId).collect(Collectors.toList());
        queryWrapper.in("employee_id", employeeIds);//是QueryWrapper的技术语句
//        wrapper.in(Resign::getEmployeeId, employeeIds);

//        queryWrapper.like(ltoQueryCondition.getName()!=null,"name", ltoQueryCondition.getName());
        queryWrapper.eq(ltoQueryCondition.getDepartmentId()!=null,"department_id", ltoQueryCondition.getDepartmentId());
        queryWrapper.like("status","通过");
        queryWrapper.select("*","COUNT(employee_id) AS count").groupBy("employee_id");

        if (month!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-01");
            String firstDay = sdf.format(month);//每月的第一天
            String lastDay = DateUtils.getLastDay(firstDay);//每月最后一天

            queryWrapper.between("over_time_date",firstDay,lastDay);
            Page<OverTimeExt> iPageExt=new Page<>();//封装
            overTimeService.page(iPage,queryWrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询
            BeanUtils.copyProperties(iPage,iPageExt,"records");//从iPage一个一个拷贝属性到iPageExt上(除了records)
            List<OverTime> records = iPage.getRecords();
            List<OverTimeExt> list = records.stream().map((item) -> {//item:遍历出来的每一个项目对象
                OverTimeExt overTimeExt = new OverTimeExt();//只有ResignExt符合项目管理页面的要求，所以new一个出来,进行填充
                BeanUtils.copyProperties(item,overTimeExt);//先填充入Resign的普通属性
                Long departmentId = item.getDepartmentId();//拿到了每个员工所对应的部门id
                Long employeeId = item.getEmployeeId();

                Employee employee = employeeService.getById(employeeId);
                Department department = departmentService.getById(departmentId);
                if(employee != null){//能查到员工
                    overTimeExt.setEmployeeName(employee.getName());//填充入employee没有的employeeName属性
                    overTimeExt.setPhone(employee.getPhone());
                }
                Position position = positionService.getById(employee.getPositionId());
                if(position != null) {
                    overTimeExt.setPosition(position.getPname());
                }

                if(department != null){//能查到员工的部门
                    String departmentName = department.getName();
                    overTimeExt.setDepartmentName(departmentName);//填充入employee没有的employeeName属性
                }
                return overTimeExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
            }).collect(Collectors.toList());//就转成集合了，赋给List<EmployeeExt> list
//            System.out.println("list里有了什么"+list);//.toString()
            iPageExt.setRecords(list);//list获得了改造过后的departmentExt集合之后，被用来设置page对象的Records属性
//        return R.success(iPageExt);
            return new Result(Code.SELECT_OK,iPageExt);
//            return overTimeMapper.selectPage(iPage,queryWrapper);
        }else {

            Page<OverTimeExt> iPageExt=new Page<>();//封装
            overTimeService.page(iPage,queryWrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询
            BeanUtils.copyProperties(iPage,iPageExt,"records");//从iPage一个一个拷贝属性到iPageExt上(除了records)
            List<OverTime> records = iPage.getRecords();
            List<OverTimeExt> list = records.stream().map((item) -> {//item:遍历出来的每一个项目对象
                OverTimeExt overTimeExt = new OverTimeExt();//只有ResignExt符合项目管理页面的要求，所以new一个出来,进行填充
                BeanUtils.copyProperties(item,overTimeExt);//先填充入Resign的普通属性
                Long departmentId = item.getDepartmentId();//拿到了每个员工所对应的部门id
                Long employeeId = item.getEmployeeId();

                Employee employee = employeeService.getById(employeeId);
                Department department = departmentService.getById(departmentId);
                if(employee != null){//能查到员工
                    overTimeExt.setEmployeeName(employee.getName());//填充入employee没有的employeeName属性
                    overTimeExt.setPhone(employee.getPhone());

                }
                Position position = positionService.getById(employee.getPositionId());
                if(position != null) {
                    overTimeExt.setPosition(position.getPname());
                }
                if(department != null){//能查到员工的部门
                    String departmentName = department.getName();
                    overTimeExt.setDepartmentName(departmentName);//填充入employee没有的employeeName属性
                }
                return overTimeExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
            }).collect(Collectors.toList());//就转成集合了，赋给List<EmployeeExt> list
//            System.out.println("list里有了什么"+list);//.toString()
            iPageExt.setRecords(list);//list获得了改造过后的departmentExt集合之后，被用来设置page对象的Records属性
            return new Result(Code.SELECT_OK,iPageExt);
        }
    }



    @GetMapping("/getOverTimeSet")
    public Result getOverTimeSet(){
        OverTimeSet overTimeSet = null;
        try {
            overTimeSet = overTimeSetService.getOverTimeSet();
//            System.out.println("overTimeSets:"+overTimeSet);
            return new Result(Code.SELECT_OK,overTimeSet);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SELECT_ERR,"加班设置查询失败！");
        }
    }

    @PutMapping("/setOverTime")
    public Result setOverTime(@RequestBody OverTimeSet overTimeSet){

        try {
            overTimeSetService.updateById(overTimeSet);
            return new Result(Code.SELECT_OK,overTimeSet,"设置成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SELECT_ERR,"加班时长设置失败！");
        }
    }

    /**
     * 通过手机号和日期查询个人的加班详情
     * @param ltoDetailCondition 查询条件
     * @return
     */
    @PostMapping("/getOverTimeDetail")
    public Result selectOverTimeDetailByPhoneAndDate(@RequestBody LTODetailCondition ltoDetailCondition) {
        String phone = ltoDetailCondition.getPhone();//手机号
        Date month = ltoDetailCondition.getMonth();//2024-3-1
        System.out.println("getOverTimeDetail传来的参数是"+ltoDetailCondition);
        QueryWrapper<OverTime> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status","通过");

        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.like(Employee::getPhone,phone);
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper1);

        List<Long> employeeIds = employeeList.stream().map(Employee::getId).collect(Collectors.toList());
        queryWrapper.in("employee_id", employeeIds);//是QueryWrapper的技术语句
//        wrapper.in(Resign::getEmployeeId, employeeIds);

        if (month!=null){

            String firstDay = month.toString();//2024-3-1
            //使用DateUtils工具类的getLastDay方法来获取某个日期的最后一天
            String lastDay = DateUtils.getLastDay(firstDay);//2024-3-31
            queryWrapper.between("over_time_date",firstDay,lastDay);

            List<OverTime> overTimes = overTimeMapper.selectList(queryWrapper);
            List<OverTimeExt> overTimeExtList = new ArrayList<>();
            for(OverTime overTime : overTimes){
                OverTimeExt overTimeExt = new OverTimeExt();

                //属性迁移
                BeanUtils.copyProperties(overTime, overTimeExt);
                System.out.println("getOverTimeDetail属性迁移完了吗1："+overTimeExt);
                //查的是多人的待审核的加班列表，所以名字要各自获得/\/\/\
                LambdaQueryWrapper<Employee> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(Employee::getId,overTime.getEmployeeId());
                Employee employee = employeeMapper.selectOne(queryWrapper2);
                if(employee != null) {
                    overTimeExt.setEmployeeName(employee.getName());
                }
                Position position = positionService.getById(employee.getPositionId());
                if(position != null) {
                    overTimeExt.setPosition(position.getPname());
                }
                overTimeExt.setPhone(employee.getPhone());
                Department department = departmentService.getById(employee.getDepartmentId());
                overTimeExt.setDepartmentName(department.getName());
                overTimeExtList.add(overTimeExt);
                System.out.println("overTimeExtList1是："+overTimeExtList);
            }
            return new Result(Code.SAVE_OK,overTimeExtList);
//            return overTimeMapper.selectList(queryWrapper);
        }else {
            List<OverTime> overTimes = overTimeMapper.selectList(queryWrapper);
            List<OverTimeExt> overTimeExtList = new ArrayList<>();
            for(OverTime overTime : overTimes){
                OverTimeExt overTimeExt = new OverTimeExt();

                //属性迁移
                BeanUtils.copyProperties(overTime, overTimeExt);
                System.out.println("getOverTimeDetail属性迁移完了吗2："+overTimeExt);
                //查的是多人的待审核的加班列表，所以名字要各自获得/\/\/\
                LambdaQueryWrapper<Employee> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(Employee::getId,overTime.getEmployeeId());
                Employee employee = employeeMapper.selectOne(queryWrapper2);
                if(employee != null) {
                    overTimeExt.setEmployeeName(employee.getName());
                }

                Position position = positionService.getById(employee.getPositionId());
                if(position != null) {
                    overTimeExt.setPosition(position.getPname());
                }
                overTimeExt.setPhone(employee.getPhone());
                Department department = departmentService.getById(employee.getDepartmentId());
                overTimeExt.setDepartmentName(department.getName());
                overTimeExtList.add(overTimeExt);
                System.out.println("overTimeExtList2是："+overTimeExtList);
            }
            return new Result(Code.SAVE_OK,overTimeExtList);
//            return overTimeMapper.selectList(queryWrapper);
        }
    }


    /**
     * 获得待审核加班列表
     * @return
     */
    @GetMapping("/getAudit")
    public Result getAudit() {

        LambdaQueryWrapper<OverTime> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OverTime::getStatus,"待审核");
        List<OverTime> overTimes = overTimeMapper.selectList(queryWrapper);


        List<OverTimeExt> overTimeExtList = new ArrayList<>();
        for(OverTime overTime : overTimes){
            OverTimeExt overTimeExt = new OverTimeExt();

            //属性迁移
            BeanUtils.copyProperties(overTime, overTimeExt);
            System.out.println("属性迁移完了吗1："+overTimeExt);
            //查的是多人的待审核的加班列表，所以名字要各自获得/\/\/\
            LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Employee::getId,overTime.getEmployeeId());
            Employee employee = employeeMapper.selectOne(queryWrapper1);
            overTimeExt.setEmployeeName(employee.getName());
            Position position = positionService.getById(employee.getPositionId());
            if(position != null) {
                overTimeExt.setPosition(position.getPname());
            }
            overTimeExt.setPhone(employee.getPhone());
            Department department = departmentService.getById(employee.getDepartmentId());
            overTimeExt.setDepartmentName(department.getName());
            overTimeExtList.add(overTimeExt);
            System.out.println("overTimeExtList是："+overTimeExtList);
        }
        return new Result(Code.SAVE_OK,overTimeExtList);
    }

    @PutMapping("/agreed/{id}/{adminId}")
    public Result agreed(@PathVariable Integer id, @PathVariable Integer adminId){
        try {
            overTimeService.agreed(id,adminId);
            return new Result(Code.UPDATE_OK,"审核成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"审核失败，请检查系统！");
        }

    }

    @PutMapping("/refuse/{id}/{adminId}")
    public Result refuse(@PathVariable Integer id,@PathVariable Integer adminId){
        try {
            overTimeService.refuse(id,adminId);
            return new Result(Code.UPDATE_OK,"审核成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"审核失败，请检查系统！");
        }

    }

    @PostMapping("/submitOverTime")
    public Result submitOverTime(@RequestBody OverTime overTime){

        try {
            overTimeService.submitOverTime(overTime);
            return new Result(Code.SAVE_OK,"上报加班记录成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SAVE_ERR,e.getMessage());
        }
    }

    @PostMapping("/getSelfOverTime/{currentPage}/{pageSize}")
    public Result getSelfOverTime(@PathVariable int currentPage,
                                  @PathVariable int pageSize,
                                  @RequestBody QuerySelfAttendanceCondition querySelfAttendanceCondition){

        IPage<OverTime> iPage = overTimeService.getSelfOverTime(currentPage,pageSize, querySelfAttendanceCondition);

        if (iPage!=null){
            return new Result(Code.SELECT_OK,iPage);
        }
        return new Result(Code.SELECT_ERR,"查询详细加班记录失败！");
    }

    @DeleteMapping("/cancelOverTime/{id}")
    public Result cancelOverTime(@PathVariable Integer id){
        try {
            overTimeService.cancelLeave(id);
            return new Result(Code.DELETE_OK,"撤销上报加班记录成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.DELETE_ERR,"撤销上报加班记录失败！");
        }
    }

}
